#!/usr/bin/env python

import sys
import os
import socket
import threading
import time

import server_connection_handler
import logging
from config import *
from logger import *

globalConnections = []

class Listener(threading.Thread):

    def __init__(self, bindIP = "0.0.0.0", bindPort = 21):

        threading.Thread.__init__(self)
        self.IP = bindIP
        self.port = bindPort
        self.listenFd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.listenFd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        self.listenFd.bind((self.IP, self.port))

        self.globalConnections = []


    def run(self):

        self.listenFd.listen(1024)

        logger.info('Server started on %s:%s' % (self.IP, str(self.port)))
        killer = idleConnKiller()

        global globalConnections

        killer.start()
        
        while True:
            recvFd, remoteAddr = self.listenFd.accept()
            logger.debug('Received connections from:%s' % remoteAddr[0])
            handler = server_connection_handler.ConnectionHandler(recvFd, remoteAddr[0])
            handler.start()

            globalConnections.append(handler)

class idleConnKiller(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.conn_lock = threading.Lock()
    
    def run(self):
        global globalConnections
        while True:
            self.conn_lock.acquire()
            try:
                currTime = time.time()
                for everyone in globalConnections:
                    if int(currTime - everyone.aliveTime) > timeout:
                        if everyone.running == True:
                            everyone.fd.shutdown(socket.SHUT_RDWR)
                        everyone.running = False

                globalConnections = [every for every in globalConnections if every.running]

            except:
                print sys.exc_info()
            self.conn_lock.release()
            time.sleep(1)
